#coding=utf-8
#!/usr/bin/env python

import MySQLdb
import sys
import os
import datetime
import psutil


db = MySQLdb.connect('127.0.0.1', 'root', '1q2w3e4r')
db.select_db('python_mysql')
cur = db.cursor()

def create_database():

	try:
		cur.execute('create table information (item CHAR(20) NOT NULL, CHAR(20),AGE INT,SEX CHAR(1),INCOME FLOAT);')
	except MySQLdb.Error,e:
		db.rollback()
		print "Mysql Error %d: %s" % (e.args[0], e.args[1])

#字节转换
def bytes2human(n):
    # http://code.activestate.com/recipes/578019
    # >>> bytes2human(10000)
    # '9.8K'
    # >>> bytes2human(100001221)
    # '95.4M'
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return "%sB" % n

###监控CPU使用率###
def getCpuPer():

	perCPU = psutil.cpu_percent(interval=1)
	print "CPU Usage：", int(perCPU), "%"
	# cur.execute('insert ')

###监控内存###
def getMemStatus():

    #获取内存状态
    phymem = psutil.phymem_usage()
    buffers = getattr(psutil, 'phymem_buffers', lambda: 0)()
    cached = getattr(psutil, 'cached_phymem', lambda: 0)()
    used = phymem.total - (phymem.free + buffers + cached)
    line = "Memory Usage: %5s%%    Used:%s    Total:%s" % (
        phymem.percent,
        str(int(used / 1024 / 1024)) + "M",
        str(int(phymem.total / 1024 / 1024)) + "M"
    )
    print line

###监控磁盘信息###
def getPartitionStatus():

    #获取磁盘分区信息
    pars = psutil.disk_partitions()
    #print ""
    print "\nDisk Partition Status:"
    templ = "%-17s %8s %8s %8s %5s%% %9s  %s"       #定义打印格式

	# 打印表头
    print templ % ("Partition", "Total", "Used", "Free", "Use", "Type",
                    "Mount")

    for par in pars:
        if os.name == "nt":
            if "cdrom" in par.opts or par.fstype == '':
                continue

        disk = psutil.disk_usage(par.mountpoint)
        print templ % (                            #打印具体的信息
            par.device,
            bytes2human(disk.total),
            bytes2human(disk.used),
            bytes2human(disk.free),
            int(disk.percent),
            par.fstype,
            par.mountpoint)

    #获取磁盘IO信息
    diskIo = psutil.disk_io_counters()
    print "\nDisk IO Status:"
    templ = "%-7s %12s %12s %12s %12s %12s"       #定义打印格式
    print templ % ("Read_Count", "Wriet_Count", "Read_Bytes",
                    "Write_Bytes", "Read_Time", "Write_Time")

    print templ % (diskIo.read_count,
                    diskIo.write_count,
                    bytes2human(diskIo.read_bytes),
                    bytes2human(diskIo.write_bytes),
                    int(diskIo.read_time/1000),
                    int(diskIo.write_time/1000))

def notice():
	notice_input = raw_input("press any key to continue or exit: ")
	if notice_input.lower() == 'exit':
		sys.exit("bye-bye")
	else:
		pass

if __name__ == '__main__':
	while True:
		print """
1.create database
2.query cpu
3.query disk
4.query memory"""+'\n'
		choose_number = raw_input("please input choose number: ")
		if choose_number == '1':
			create_database()
			notice()
		elif choose_number == '2':
			getCpuPer()
		elif choose_number == '3':
			getMemStatus()
		elif choose_number == '4':
			getPartitionStatus()
		else:
			print "Sorry, error input, please try again. "
